﻿using System;
using System.Web;
using System.Web.Caching;

namespace AllInOnePluginBL.Helpers
{
    /// <summary>
    /// Summary description for CacheManager
    /// </summary>
    public sealed class CacheManager
    {
        private readonly object _lock_object = new object();
        private readonly HttpContext _current;

        #region Ctor
        CacheManager()
        {
            _current = HttpContext.Current;
        }

        public static CacheManager Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        class Nested
        {
            // Explicit static constructor to tell C# compiler
            // not to mark type as beforefieldinit
            static Nested()
            {
            }

            internal static readonly CacheManager instance = new CacheManager();
        } 
        #endregion

        public bool IsInCache(string key)
        {
            return GetData(key) != null;
        }

        public object GetData(string key)
        {
            lock (_lock_object)
            {
                return _current == null ? null : _current.Cache[key];
            }
        }

        public void CacheData(string key, object val, DateTime expirationTimein)
        {
            lock (_lock_object)
            {
                if (_current == null) return;
                _current.Cache.Insert(key, val, null, expirationTimein, Cache.NoSlidingExpiration);
            }
        }

        public void SetCacheExperiation(HttpResponse response, TimeSpan freshness)
        {
            var now = DateTime.Now;
            response.Cache.SetExpires(now.Add(freshness));
            response.Cache.SetMaxAge(freshness);
            response.Cache.SetCacheability(HttpCacheability.Server);
            response.Cache.SetValidUntilExpires(true);
        }
    }
}